package cn.lingyangwl.agile.gateway.filter;

import cn.lingyangwl.framework.core.http.HttpRequestReactiveManager;
import cn.lingyangwl.framework.core.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
public class LoggingFilter implements GlobalFilter, Ordered {
    private static final String START_TIME = "startTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("method: {}, host: {}, ip: {}, path: {}",
                Optional.ofNullable(exchange.getRequest().getMethod()).map(Enum::name).orElse(""),
                exchange.getRequest().getURI().getHost(),
                IpUtils.getRequestIp(new HttpRequestReactiveManager(exchange)),
                exchange.getRequest().getURI().getPath());

        return chain.filter(exchange).then( Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                long executeTime = (System.currentTimeMillis() - startTime);
                log.info("time: {} ms, path: {}", executeTime, exchange.getRequest().getURI().getRawPath());
            }
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
